package com.pt25.base.util;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class TreeUtil {

    public static <T extends Tree> List<T> toTree(List<T> list, Long parentId) {
        List<T> menus = new ArrayList<>();
        for (T t : list) {
            Long menuId = t.getId();
            Long pId = t.getParentId();
            if (parentId.equals(pId)) {
                List<T> menuLists = toTree(list, menuId);
                t.setChildren(menuLists);
                if (t.getChildren().isEmpty()) {
                    //最后一层设置children为空
                    t.setChildren(null);
                }
                menus.add(t);
            }
        }
        return menus;
    }

    @Data
    public static class Tree {
        private Long id;
        @JsonFormat(shape = JsonFormat.Shape.STRING)
        private Long parentId;
        private List<?> children;
    }
}
